/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
 * main.c
 * Copyright (C) widebright 2009 <widebright@gmail.com>
 * 
 * main.c is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * main.c is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along
 * with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
//#include <config.h>

#include <gtk/gtk.h>

static gint timer_min;
static gint timer_sec;

static int lock_seconds;
static int unlock_minutes;
static gboolean  is_desktop_lock;


GtkLabel  * label_message;
GtkLabel  * label_time_left;
GtkWidget * window;
GtkMenu   * menu1;


gint every_minute_callback (gpointer data);
gint every_second_callback (gpointer data);
void lock_desktop(int lock_time);
void unlock_desktop();
GtkWidget* create_window (void);
char * get_exe_path(); 

/*
 * Standard gettext macros.
 */
#ifdef ENABLE_NLS
#  include <libintl.h>
#  undef _
#  define _(String) dgettext (PACKAGE, String)
#  ifdef gettext_noop
#    define N_(String) gettext_noop (String)
#  else
#    define N_(String) (String)
#  endif
#else
#  define textdomain(String) (String)
#  define gettext(String) (String)
#  define dgettext(Domain,Message) (Message)
#  define dcgettext(Domain,Message,Type) (Message)
#  define bindtextdomain(Domain,Directory) (Domain)
#  define _(String) (String)
#  define N_(String) (String)
#endif



/* For testing propose use the local (not installed) glade file */
/* #define GLADE_FILE PACKAGE_DATA_DIR"/relax_reminder/glade/relax_reminder.glade" */
#define GLADE_FILE "relax_reminder.glade"
	
GtkWidget*
create_window (void)
{
	GtkWidget *window;
    GtkBuilder * builder;

	char *exe_path=get_exe_path();
	if (exe_path ==NULL)
	{
	    perror("不能获取到程序的目录");
        exit(1);
	}

	strcat (exe_path , "relax_reminder.glade");
    builder = gtk_builder_new ();
    if (0 == gtk_builder_add_from_file (builder,exe_path,NULL))
    {
         printf("不能加载程序界面文件 %s \n",exe_path);
         exit(1);
    }
    free(exe_path);
	  
    gtk_builder_connect_signals(builder,"mysignal_data");

	window = (GtkWidget *) gtk_builder_get_object (builder, "window");
		
	//GdkColor window_bk={0,0,0,0};
	//GdkColor window_bk={0,55535,65535,55535};
    GdkColor window_bk={0, 26728,19275,13107};
	
	gtk_widget_modify_bg(window,
						 GTK_STATE_NORMAL //|GTK_STATE_ACTIVE|GTK_STATE_PRELIGHT|
						 //GTK_STATE_SELECTED|GTK_STATE_INSENSITIVE
			            ,&window_bk);			 

	menu1 =(GtkMenu *) gtk_builder_get_object (builder, "menu1");
		
	label_message =   ( GtkLabel *) gtk_builder_get_object (builder,  "label_message");
	label_time_left = ( GtkLabel *) gtk_builder_get_object (builder,  "label_time_left");

    
	PangoAttribute*   font =pango_attr_scale_new  (2.5);
	//PangoAttribute*   bk_color =pango_attr_background_new  (65535,65535,65535);
	PangoAttribute*   font_color =pango_attr_foreground_new  (0,50000,0);
	PangoAttrList * attrs =pango_attr_list_new ();
	//pango_attr_list_insert (attrs, bk_color);
	pango_attr_list_insert (attrs, font_color);
    pango_attr_list_insert (attrs, font);

	
    gtk_label_set_attributes(label_message,attrs);
	gtk_label_set_attributes(label_time_left,attrs);
    pango_attr_list_unref (attrs);
	
	
	return window;
}
void lock_desktop(int lock_time)
{   
    is_desktop_lock=TRUE;
	lock_seconds = lock_time;
	g_source_remove(timer_min);
    timer_sec = g_timeout_add(1000,every_second_callback,NULL);
	

    //  gtk_window_present 做的事情等于  gtk_window_deiconify  + gtk_widget_show +  gtk_widget_activate 等等
    gtk_window_present ((GtkWindow *)window);
    // gtk_window_deiconify ((GtkWindow *)window);  //反图标化，从最小化中还原回来,在最小化的时候，调用gtk_window_maximize  而不先调用这个是不行的。
	//gtk_widget_show (window);
    //gtk_widget_activate (window);
    gtk_window_maximize ((GtkWindow *)window);
	//窗体透明度
	gtk_window_set_opacity (GTK_WINDOW(window),0.6);
	//去掉标题栏
	//gtk_window_set_decorated (GTK_WINDOW(window),FALSE);
	//全屏窗口
    gtk_window_fullscreen(GTK_WINDOW(window));
	//置顶窗口
	gtk_window_set_keep_above(GTK_WINDOW(window),TRUE);
	
	//禁止其他程序获得键盘消息
	//gdk_keyboard_grab(window->window ,TRUE,GDK_CURRENT_TIME);其他程序也可以受到消息
	if(GDK_GRAB_SUCCESS !=gdk_keyboard_grab(window->window ,FALSE,GDK_CURRENT_TIME)) // 其他程序不能收到消息
	{
	  sleep(1); //如果第一次请求不成功，等会在重试，
	  if(GDK_GRAB_SUCCESS !=gdk_keyboard_grab(window->window ,FALSE,GDK_CURRENT_TIME)) // 其他程序不能收到消息
	  {
	    sleep(2);
	   if(GDK_GRAB_SUCCESS !=gdk_keyboard_grab(window->window ,FALSE,GDK_CURRENT_TIME)) // 其他程序不能收到消息
	   {
	    	sleep(3);
	   		gdk_keyboard_grab(window->window ,FALSE,GDK_CURRENT_TIME);
	   }
	  }
	}

//注意grab函数并不能禁止重启xorg的快捷方式
//#往/etc/X11/xorg.conf文件里面加如下面内容，我的是没有这个文件，
//#所以要新建一个xorg.conf文件     
//#参见man xorg.conf 看更多的说明
//
//#---------------------------------------
//#禁用重启xorg的键盘快捷键
//Section "ServerFlags"
//        Option "DontVTSwitch"  "true"
//        Option "DontZap"  "true"
//        Option "DontZoom"  "true" 
//EndSection
//#-----------------------------------------



}

void unlock_desktop()
{
	is_desktop_lock=FALSE;
	//释放键盘
	gdk_keyboard_ungrab(GDK_CURRENT_TIME);
		
	gtk_widget_hide (window);
	gtk_label_set_text(label_time_left,"");
	gtk_label_set_text(label_message,"widebright的休息提醒小程序");
	
    g_source_remove(timer_sec);
    timer_min = g_timeout_add(1000*60,every_minute_callback,NULL);
	

}

gint every_minute_callback (gpointer data)
{
    char messages[128];
	
    unlock_minutes ++;
	snprintf ( messages,128,"时间过去了%d分钟", unlock_minutes);
	gtk_label_set_text(label_time_left,messages);
	gtk_label_set_text(label_message,"widebright的休息提醒小程序");
	
	if  (unlock_minutes % 60 ==0)
	{    		
		 unlock_minutes =0;
	     lock_desktop(60 *10);
	     gtk_label_set_text(label_message,"休息十分钟^_^");
	}
	else if (unlock_minutes % 20 ==0)
    // else if (unlock_minutes % 1 ==0)
	{
	    // lock_desktop(5);
	     lock_desktop(60*2);
		 gtk_label_set_text(label_message,"休息两分钟^_^");
	}
    return TRUE;
}

gint every_second_callback (gpointer data)
{
    char messages[128];
	snprintf ( messages,128,"还剩下 %d分%d秒",lock_seconds/60,lock_seconds%60);
	gtk_label_set_text(label_time_left,messages);	
	
	lock_seconds -- ;
	if (lock_seconds ==0)
	{
	     unlock_desktop();
	}
		
    return TRUE;
}

static gboolean
tray_button_pressed (GtkWidget * widget, GdkEventButton * event,
			     GtkStatusIcon * tray_icon)
{
	g_return_val_if_fail (tray_icon, FALSE);
	g_return_val_if_fail ((event->type == GDK_BUTTON_PRESS), FALSE);  

	switch (event->button)
	{
	case 1:  //left button
        if (GTK_WIDGET_VISIBLE(window))
		{
		   gtk_widget_hide (window);
		}
		else
		{
		   gtk_window_unfullscreen(GTK_WINDOW(window));
		   gtk_window_unmaximize(GTK_WINDOW(window));	
		   gtk_window_deiconify (GTK_WINDOW(window));
		   gtk_widget_show (window);
		   gtk_window_resize(GTK_WINDOW(window),
                                           500,
                                           400);

		   // gtk_widget_set_size_request ((GtkWidget *)window,
           //                                         500,
           //                                         400);
		}
		break;
	case 2:// middle button
		break;
	case 3: //right button
	 
		gtk_menu_popup (menu1, NULL, NULL, NULL, NULL,
				event->button, event->time);
		break;
	default:

       /* Tell calling code that we have not handled this event; pass it on. */
       return FALSE;
	}
        /* Tell calling code that we have handled this event; the buck
         * stops here. */
	return TRUE;
}



void on_menuitem1_toggled  (GtkCheckMenuItem * menuitem, gpointer user_data)
{
	
    if (gtk_check_menu_item_get_active (menuitem) )
	{
	   //gtk_label_set_text(label_time_left,"选中");
	   g_source_remove(timer_min);
	   		
	}
	else
	{
	   //gtk_label_set_text(label_time_left,"没选中");
	   timer_min = g_timeout_add(1000*60,every_minute_callback,NULL);
	}
	printf ("停止计时器\n");				
}

void on_menuitem4_activate(GtkMenuItem *menuitem,  gpointer  user_data)
{
    unlock_minutes = 0;
	gtk_label_set_text(label_time_left,"");
	gtk_label_set_text(label_message,"widebright的休息提醒小程序");
	printf ("清零\n");		 
	//禁止其他程序获得键盘消息
	//gdk_keyboard_grab(window->window ,FALSE,GDK_CURRENT_TIME);
}
gboolean main_windows_on_delete (GtkWidget *widget)
{
     if (is_desktop_lock){
	     return TRUE;
	 }else{
         return gtk_widget_hide_on_delete (widget);
	 }
 
}

//获取程序的文件所在的目录
char * get_exe_path()
{
  char *path = malloc(1024 * sizeof(char));
  int count = readlink("/proc/self/exe",path, 1024);
  if( count < 0 )
  {
	  *path = '\0'; 
       free(path);
       return NULL;
  }

  // 注意readlink不会字符串结尾添加'\0' 这个字符串结束标志
  path[count] = '\0';

  char *p = strrchr(path,'/');
  *++p ='\0';
  //printf("current   working   directory   :   %s\n",path);  
  return path;
}



int
main (int argc, char *argv[])
{
    GtkStatusIcon * tray_icon;
	char *exe_path ;
	
#ifdef ENABLE_NLS
	bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
	textdomain (GETTEXT_PACKAGE);
#endif

	
	gtk_set_locale ();
	gtk_init (&argc, &argv);

	window = create_window ();
	gtk_window_set_title(GTK_WINDOW(window), "休息提醒小程序");
	
	gtk_widget_show (window);
	exe_path =  get_exe_path();
	if (exe_path == NULL)
	{
	   perror("不能获取到程序的目录\n");
       exit(1);
	}
	strcat (exe_path , "widebright.png");
    printf("图片文件名=%s\n", exe_path);
	gtk_window_set_icon_from_file(GTK_WINDOW(window), exe_path,NULL);
	
    free(exe_path);
	//窗体透明度
	//gtk_window_set_opacity (GTK_WINDOW(window),0.5);
	//全屏窗口
    //gtk_window_fullscreen(GTK_WINDOW(window));
	//置顶窗口
	//gtk_window_set_keep_above(GTK_WINDOW(window),TRUE);
	//去掉标题栏
	//gtk_window_set_decorated (GTK_WINDOW(window),FALSE);
 	
	exe_path=get_exe_path();
	if (exe_path ==NULL)
	{
	   perror("不能获取到程序的目录");
       exit(1);
	}
	strcat (exe_path , "widebright.png");

    tray_icon = gtk_status_icon_new_from_file(exe_path);
	if (tray_icon == NULL)
    {
            perror("不能创建托盘图标");
            exit(1);
    }
    free(exe_path);
    //gtk_status_icon_set_name ( tray_icon, "widebright tray icon");
	
	g_signal_connect (G_OBJECT (tray_icon), "button-press-event",
			  G_CALLBACK (tray_button_pressed), tray_icon);

	gtk_status_icon_set_tooltip_text(tray_icon ,"widebright 的休息提醒程序");
    gtk_status_icon_set_visible (tray_icon, TRUE);
    //gtk_widget_show_all (GTK_WIDGET (tray_icon)); 
	
    is_desktop_lock =FALSE;
    lock_seconds = 0 ;
    unlock_minutes = 0;
	gtk_label_set_text(label_time_left,"");
	gtk_label_set_text(label_message,"widebright的休息提醒小程序");
	timer_min = g_timeout_add(1000*60,every_minute_callback,NULL);
	
    gtk_widget_hide (window);
   	gtk_main ();
	return 0;
}
